<template>
    <div class="user-management">
      <!-- 搜索栏 -->
      <el-card class="search-box">
        <div class="search-container">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入用户名或昵称搜索"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </el-card>
  
      <!-- 用户表格 -->
      <el-card class="user-table">
        <el-table 
          :data="userList" 
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column label="头像" width="80">
            <template #default="{ row }">
              <el-avatar 
                :src="'http://localhost:8092' + row.avatar" 
                :size="40"
              />
            </template>
          </el-table-column>
          
          <el-table-column prop="username" label="用户名" width="120" />
          
          <el-table-column prop="nickname" label="昵称" width="120">
            <template #default="{ row }">
              <el-tag v-if="!row.nickname" type="info">未设置</el-tag>
              <span v-else>{{ row.nickname }}</span>
            </template>
          </el-table-column>
        
          <el-table-column prop="school" label="学校" width="180" />
        <el-table-column prop="grade" label="年级" width="100" />
          <el-table-column label="角色" width="100">
            <template #default="{ row }">
              <el-tag :type="roleTagType(row.role)">
                {{ formatRole(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
  
          <!-- <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.loginStatus === '1' ? 'success' : 'danger'">
                {{ row.loginStatus === '1' ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column> -->
  
          <el-table-column label="联系方式" min-width="180">
            <template #default="{ row }">
              <div class="contact-info">
                <div v-if="row.phone">
                  <el-icon><Iphone /></el-icon>
                  {{ row.phone }}
                </div>
                <div v-if="row.email">
                  <el-icon><Message /></el-icon>
                  {{ row.email }}
                </div>
              </div>
            </template>
          </el-table-column>
  
      <el-table-column prop="credit" label="信用分" width="120">
  <template #header>
    <span>
      信用分
      <el-tooltip effect="dark" placement="top">
        <template #content>
          <div style="max-width: 200px">
            信用等级说明：<br/>
            • 0-150分: 差（红色）<br/>
            • 150-300分: 良好（黄色）<br/>
            • 300分以上: 优秀（绿色）
          </div>
        </template>
        <el-icon style="margin-left:5px;cursor: pointer"><Warning /></el-icon>
      </el-tooltip>
    </span>
  </template>
  <template #default="{ row }">
    <el-tag 
      :type="getCreditTagType(row.credit)"
      effect="dark"
    >
      {{ getCreditStatus(row.credit) }}
    </el-tag>
  </template>
</el-table-column>
  
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(row.userId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <!-- 编辑对话框 -->
      <el-dialog 
        v-model="editDialogVisible" 
        title="编辑用户信息"
        width="600px"
         @closed="handleDialogClose"
      >
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
            >
            <img 
                  v-if="editForm.avatar" 
                  :src="avatarFile ? editForm.avatar : 'http://localhost:8092' + editForm.avatar" 
                  class="avatar"
                >
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
  
          <el-form-item label="昵称">
            <el-input v-model="editForm.nickname" />
          </el-form-item>
  
          <el-form-item label="性别">
            <el-select v-model="editForm.sex">
              <el-option label="男" value="01" />
              <el-option label="女" value="02" />
            </el-select>
          </el-form-item>
          <el-form-item label="学校">
          <el-autocomplete
            v-model="editForm.school"
            :fetch-suggestions="fetchSchools"
            clearable
            placeholder="请输入学校"
            @select="handleSchoolSelect"
          />
        </el-form-item>

        <!-- 新增年级编辑 -->
        <el-form-item label="年级">
          <el-select v-model="editForm.grade" placeholder="请选择年级">
            <el-option
              v-for="option in gradeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
          <el-form-item label="专业">
            <el-input v-model="editForm.major" />
          </el-form-item>
  
          <el-form-item label="联系电话">
            <el-input v-model="editForm.phone" />
          </el-form-item>
  
          <el-form-item label="电子邮箱">
            <el-input v-model="editForm.email" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认修改</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, } from 'element-plus'
  import { Warning } from '@element-plus/icons-vue'
  import axios from 'axios'
  const avatarFile = ref(null)
  const searchKeyword = ref('')
  const userList = ref([])
  const loading = ref(false)
  const editDialogVisible = ref(false)
  const editForm = ref({
    userId: null,
    nickname: '',
    sex: '',
    major: '',
    phone: '',
    email: '',
    avatar: '',
    school: '',
    grade: ''
  })
  const gradeOptions = [
  { value: '大一', label: '大一' },
  { value: '大二', label: '大二' },
  { value: '大三', label: '大三' },
  { value: '大四', label: '大四' },
  { value: '研一', label: '研一' },
  { value: '研二', label: '研二' },
  { value: '研三', label: '研三' }
]
const fetchSchools = async (queryString, cb) => {
  if (!queryString) return cb([])
  try {
    const response = await axios.get('http://localhost:8092/school/list')
    const results = response.data.filter((school) =>
      school.schoolname.toLowerCase().includes(queryString.toLowerCase())
    )
    cb(results.map((school) => ({ value: school.schoolname })))
  } catch (error) {
    console.error('Error fetching schools:', error)
    cb([])
  }
}
const getCreditStatus = (credit) => {
  if (credit <= 150) return `差 (${credit}分)`
  if (credit <= 300) return `良好 (${credit}分)`
  return `优秀 (${credit}分)`
}

const getCreditTagType = (credit) => {
  if (credit <= 150) return 'danger'
  if (credit <= 300) return 'warning'
  return 'success'
}
const handleSchoolSelect = (school) => {
  editForm.value.school = school.value
}
  // 获取用户列表
  const fetchUsers = async (keyword = '') => {
    try {
      loading.value = true
      const { data } = await axios.get('http://localhost:8092/user/list', )
      if (data.code === 200) {
        userList.value = data.data
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }
  const handleAvatarChange = (uploadFile) => {
  // 清空之前的文件缓存
  avatarFile.value = null

  // 验证文件类型和大小
  const isImage = uploadFile.raw.type.startsWith('image/')
  const isLt2M = uploadFile.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }

  // 生成预览图（使用Blob URL提升性能）
  const blobURL = URL.createObjectURL(uploadFile.raw)
  editForm.value.avatar = blobURL
  
  // 保存原始文件对象
  avatarFile.value = uploadFile.raw
  return false
}
const handleDialogClose = () => {
  editDialogVisible.value = false
  // 清理Blob URL
  if (avatarFile.value) {
    URL.revokeObjectURL(editForm.value.avatar)
  }
  avatarFile.value = null
}
  // 搜索处理
  const handleSearch = () => {
    fetchUsers(searchKeyword.value)
  }
  
  // 删除用户
  const handleDelete = async (userId) => {
    try {
      await ElMessageBox.confirm('确认删除该用户？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      const { data } = await axios.delete(`http://localhost:8092/user/delete/${userId}`)
      if (data.code === 200) {
        ElMessage.success('删除成功')
        fetchUsers()
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
  
  // 打开编辑对话框
  const handleEdit = (user) => {
    editForm.value = {
        userId: user.userId,
         ...user }
    editDialogVisible.value = true
  }
  
  // 提交编辑

  const submitEdit = async () => {
  try {
    const formData = new FormData()
    
    // 添加用户ID
    formData.append('userId', editForm.value.userId)
    
    // 添加文本字段
    const fields = ['nickname', 'sex', 'major', 'phone', 'email', 'school', 'grade']
    fields.forEach(field => {
      formData.append(field, editForm.value[field] || '')
    })

    // 添加头像文件
    if (avatarFile.value) {
      formData.append('avatar', avatarFile.value)
    }

    // 调试输出表单数据
    for (let [key, value] of formData.entries()) {
      console.log(key, value)
    }

    // 发送请求
    const { data } = await axios.post(
      'http://localhost:8092/user/updateUser',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }
    )
    
    if (data.code === 200) {
      ElMessage.success('修改成功')
      // 刷新列表并重置状态
      editDialogVisible.value = false
      avatarFile.value = null
      await fetchUsers()
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(`修改失败: ${error.response?.data?.message || '服务器错误'}`)
  }
}
  
  // 头像上传处理
  const handleAvatarSuccess = (response) => {
    if (response.code === 200) {
      editForm.value.avatar = response.data.avatar
    }
  }
  
  const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
  
    if (!isImage) {
      ElMessage.error('只能上传图片文件')
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过2MB')
    }
    return isImage && isLt2M
  }
  
  // 格式化显示
  const formatRole = (role) => {
    const roleMap = {
      '00': '管理员',
      '01': '学生',
      '02': '教师'
    }
    return roleMap[role] || '未知角色'
  }
  
  const roleTagType = (role) => {
    const typeMap = {
      '00': 'danger',
      '01': 'success',
      '02': 'warning'
    }
    return typeMap[role] || 'info'
  }
  
  onMounted(() => {
    fetchUsers()
  })
  </script>
  
  <style lang="scss" scoped>
  .user-management {
    padding: 24px;
    
    .search-box {
      margin-bottom: 16px;
      
      .search-container {
        display: flex;
        gap: 16px;
      }
    }
  
    .user-table {
      :deep(.el-table__cell) {
        padding: 12px 0;
      }
  
      .contact-info {
        display: flex;
        flex-direction: column;
        gap: 8px;
  
        div {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
  
    .avatar-uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
  
        &:hover {
          border-color: var(--el-color-primary);
        }
      }
  
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        text-align: center;
        line-height: 120px;
      }
  
      .avatar {
        width: 120px;
        height: 120px;
        display: block;
        object-fit: cover;
      }
    }
  }
  </style>